package com.example.fw;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.ContactData;

public class ContactHelper extends HelperBase {


	public ContactHelper(ApplicationManager manager) {
		super(manager);
	}

	public void initContactCreation() {
		click(By.linkText("add new"));
	}

	public void fillContactFields(ContactData contact) {
		type(By.name("firstname"), contact.name);
		type(By.name("lastname"), contact.surname);
		type(By.name("address"), contact.address);		
		type(By.name("home"), contact.homePhone);
		type(By.name("mobile"), contact.mobilePhone);
		type(By.name("work"), contact.workPhone);
		type(By.name("email"), contact.email);
		type(By.name("email2"), contact.email2);
	    selectByText(By.name("bday"), contact.birthDay);
	    selectByText(By.name("bmonth"), contact.birthMonth);		   
	    type(By.name("byear"), contact.birthYear);
//	    selectByText(By.name("new_group"), contact.contactGroup);
	}

	public void submitContactCeation() {
		click(By.name("submit"));
	}
	
	public void returnToHomePage() {
		click(By.linkText("home page"));
	}

	public void deleteContact() {
		click(By.xpath("/html/body/div/div[4]/form[2]/input[2]"));
		
	}

	private void selectContactByIndex(int index) {
		click(By.xpath("//input[@name='selected[]']["+ (index+1) +"]"));
		
	}

	public void initContactModification(int index) {
		selectContactByIndex(index);
		index = index+2;
		click(By.xpath("//table/tbody/tr["+ index +"]/td[7]/a/img"));
	
	}

	public void submitContactModification() {
		click(By.xpath("/html/body/div/div[4]/form/input[11]"));
		
	}

	public List<ContactData> getContacts() {
		List<ContactData> contacts = new ArrayList<ContactData>();
	    List<WebElement> checkboxes = driver.findElements(By.name("selected[]"));
	    for (WebElement checkbox : checkboxes) {
			ContactData contact = new ContactData();
			String title = checkbox.getAttribute("title");
			String textTitle = title.substring("Select (".length(), title.length() - ")".length());
			String[] splitTitle = textTitle.split(" ");
			contact.name = splitTitle[0];
			contact.surname = splitTitle[1];
			contacts.add(contact);
		}		
		return contacts;
	}

}
